﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Demo_jwt_core2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class AuthController  : ControllerBase
    {
        [HttpGet]
        public IActionResult Get(string userName, string pwd)
        {
            //此处只简单的验证用户名和密码的不为空，实际中使用时不要这样
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
            {
                //Header
                var header = "{\"alg\": \"HS256\",\"typ\": \"JWT\"}";
                var headerBase = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(header));

                //Payload
                var payloadDic = new Dictionary<string, object>();
                payloadDic["iss"]= Const.Domain;
                //添加jwt可用时间
                var now = DateTime.UtcNow;
                payloadDic["nbf"] = now.ToUniversalTime();//可用时间起始
                payloadDic["exp"] = now.AddMinutes(30).ToUniversalTime();//可用时间结束
                var payload = JsonConvert.SerializeObject(payloadDic);
                var payloadBase = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(payload));

                //Signature
                //声明hs256对象
                var hs256 = new HMACSHA256(Encoding.UTF8.GetBytes(Const.SecurityKey));
                //生成signature
                var signature = hs256.ComputeHash(Encoding.UTF8.GetBytes(headerBase + "." + payloadBase));
                var signatureBase = Base64UrlTextEncoder.Encode(signature);
                return Ok(new
                {
                    token = headerBase + "." + payloadBase + "." + signatureBase
                }) ;
            }
            else
            {
                return BadRequest(new { message = "username or password is incorrect." });
            }
        }
    }
}
